import { Component, OnInit, Input, AfterViewInit, OnChanges, SimpleChanges } from '@angular/core';
import MVT from 'ol/format/MVT';
import VectorTileLayer from 'ol/layer/VectorTile';
import VectorTileSource from 'ol/source/VectorTile';
import { Fill, Stroke, Style } from 'ol/style';
import { unByKey } from 'ol/Observable';
import { Map } from 'ol';
import * as _ from 'lodash';
import { UtilComponent } from '../../interface/util-component.interface';

@Component({
  selector: 'kylin-vector-block-selection',
  templateUrl: './vector-block-selection.component.html',
  styleUrls: ['./vector-block-selection.component.css']
})
export class VectorBlockSelectionComponent implements OnInit, AfterViewInit, OnChanges, UtilComponent {
  // ---------- 接口实现 begin -------------- //
  hasContent = true;
  map: Map;

  @Input() set data(val) {
    Object.assign(this, val);
  };

  // ---------- 接口实现 end ---------------- //{
  private vtLayer: any;
  private clickEventKey: any;

  constructor() {

  }

  ngOnChanges(changes: SimpleChanges): void {
    if (!_.isEmpty(changes.map.currentValue)) {
      // this.add();
    }

  }

  ngOnInit() {

  }
  ngAfterViewInit() {

  }

  add() {
    if (this.vtLayer) {
      return;
    }

    let selection = {};
    const idProp = 'iso_a3';

    this.vtLayer = new VectorTileLayer({
      declutter: true,
      source: new VectorTileSource({
        format: new MVT(),
        url: 'https://ahocevar.com/geoserver/gwc/service/tms/1.0.0/ne:ne_10m_admin_0_countries@EPSG%3A900913@pbf/{z}/{x}/{-y}.pbf'
      }),
      style: (feature) => {
        const selected = !!selection[feature.get(idProp)];
        return new Style({
          stroke: new Stroke({
            color: selected ? 'rgba(200,20,20,0.8)' : 'gray',
            width: selected ? 2 : 1
          }),
          fill: new Fill({
            color: selected ? 'rgba(200,20,20,0.2)' : 'rgba(20,20,20,0.9)'
          })
        });
      }
    });

    this.map.addLayer(this.vtLayer);

    this.clickEventKey = this.map.on('click', (event) => {
      const features = this.map.getFeaturesAtPixel(event.pixel);
      if (!features) {
        selection = {};
        this.vtLayer.setStyle(this.vtLayer.getStyle());
        return;
      }
      const feature = features[0];
      const fid = feature.get(idProp);
      selection[fid] = feature;
      this.vtLayer.setStyle(this.vtLayer.getStyle());
    });

  }

  cancel(options?: any): any {
    this.map.removeLayer(this.vtLayer);
    unByKey(this.clickEventKey);
    this.vtLayer = null;
  }


}
